<template>
  <div class="dashboard-container">
    <el-card shadow="never">
      <el-row justify="space-between">
        <el-col :span="18" :xs="24">
          <div class="flex h-full items-center">
            <Avatar :avatarUrl="userStore.user.avatar" @updateAvatar="updateAvatar"></Avatar>
            <div style="margin-left: 5px">
              <p>{{ greetings }}</p>
            </div>
          </div>
        </el-col>

        <el-col :span="6" :xs="24">
          <div class="flex h-full items-center justify-around">
            <el-statistic v-for="item in statisticData" :key="item.key" :value="item.value">
              <template #title>
                <div class="flex items-center">
                  <svg-icon :icon-class="item.iconClass" size="20px" />
                  <span class="text-[16px] ml-1">{{ item.title }}</span>
                </div>
              </template>
              <template v-if="item.suffix" #suffix>/100</template>
            </el-statistic>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据卡片 -->
    <el-row :gutter="10" class="mt-3">
      <el-col :xs="24" :sm="12" :lg="8" v-for="(item, index) in cardData" :key="index">
        <el-card shadow="never">
          <template #header>
            {{ item.title }}
          </template>
          <CircleProgressChart :id="`system-monitor-${index}`" :title="item.title" :value="Math.round(item.count)"
            :color="item.tagType === 'primary' ? '#409EFF' : item.tagType === 'warning' ? '#E6A23C' : '#F56C6C'"
            height="200px" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统详细信息 -->
    <el-card shadow="never" class="mt-3" v-loading="loading">
      <template #header>
        <div class="flex items-center">
          <svg-icon icon-class="system" size="20px" />
          <span class="ml-2">系统详细信息</span>
        </div>
      </template>
      <!-- 操作系统信息组 -->
      <el-descriptions :column="1" border>
        <template #title>
          <div class="flex items-center mb-2">
            <svg-icon icon-class="system" size="16px" />
            <span class="ml-2 font-bold">操作系统信息</span>
          </div>
        </template>
        <el-descriptions-item label="操作系统">
          <div class="flex items-center">
            <span class="ml-2">{{ osName }}</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="系统版本">
          <div class="flex items-center">
            <span class="ml-2">{{ osVersion }}</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="系统架构">
          <div class="flex items-center">
            <span class="ml-2">{{ osArch }}</span>
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- CPU信息组 -->
      <el-descriptions :column="1" border class="mt-4">
        <template #title>
          <div class="flex items-center mb-2">
            <svg-icon icon-class="cpu" size="16px" />
            <span class="ml-2 font-bold">CPU信息</span>
          </div>
        </template>
        <el-descriptions-item label="CPU核心数">
          <div class="flex items-center">
            <span class="ml-2">{{ cpuNum }}</span>
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 内存信息组 -->
      <el-descriptions :column="1" border class="mt-4">
        <template #title>
          <div class="flex items-center mb-2">
            <svg-icon icon-class="memory" size="20px" />
            <span class="ml-2 font-bold">内存信息</span>
          </div>
        </template>
        <el-descriptions-item label="总内存">
          <div class="flex items-center">
            <span class="ml-2">{{ memoryTotal }} GB</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="已用内存">
          <div class="flex items-center">
            <span class="ml-2">{{ memoryUsed }} GB</span>
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 磁盘信息组 -->
      <el-descriptions :column="1" border class="mt-4">
        <template #title>
          <div class="flex items-center mb-2">
            <svg-icon icon-class="disk" size="19px" />
            <span class="ml-2 font-bold">磁盘信息</span>
          </div>
        </template>
        <template v-for="(disk, path) in diskInfo" :key="path">
          <el-descriptions-item :label="`磁盘${path}`">
            <div class="flex items-center">
              <span class="ml-2">总容量: {{ disk.total || '-' }} GB</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item :label="`已用空间${path}`">
            <div class="flex items-center">
              <span class="ml-2">{{ disk.used || '-' }} GB</span>
            </div>
          </el-descriptions-item>
        </template>
      </el-descriptions>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { getSystemInfoApi } from "@/api/sysinfo/index";
import Avatar from "@/components/Avatar/index.vue";
import { useUserStore } from "@/store/modules/user";
import { TransitionPresets, useTransition } from "@vueuse/core";
import type { EpPropMergeType } from "element-plus/es/utils/vue/props/types";
import CircleProgressChart from "./components/CircleProgressChart.vue";

defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});


interface CardProp {
  title: string;
  tagType: EpPropMergeType<
    StringConstructor,
    "primary" | "success" | "info" | "warning" | "danger",
    unknown
  >;
  tagText: string;
  count: any;
  dataDesc: string;
  iconClass: string;
}

const userStore = useUserStore();
const date: Date = new Date();
// 系统信息相关的响应式变量
const loading = ref(true);
const osName = ref<string>('-');
const osVersion = ref<string>('-');
const osArch = ref<string>('-');
const cpuNum = ref<number | string>('-');
const memoryTotal = ref<number | string>('-');
const memoryUsed = ref<number | string>('-');
const diskInfo = ref<Record<string, { total: number | string; used: number | string }>>({});

const greetings = computed(() => {
  const hours = date.getHours();
  if (hours >= 6 && hours < 12) {
    return "上午好，" + userStore.user.nickname + "！";
  } else if (hours >= 12 && hours < 18) {
    return "下午好，" + userStore.user.nickname + "！";
  } else if (hours >= 18 && hours < 24) {
    return "晚上好，" + userStore.user.nickname + "！";
  }
});

const duration = 5000;

// CPU使用率
const cpuUsage = ref(0);
const cpuUsageOutput = useTransition(cpuUsage, {
  duration: duration,
  transition: TransitionPresets.easeOutExpo,
});

// 内存使用率
const memoryUsage = ref(0);
const memoryUsageOutput = useTransition(memoryUsage, {
  duration: duration,
  transition: TransitionPresets.easeOutExpo,
});

// 磁盘使用率
const diskUsage = ref(0);
const diskUsageOutput = useTransition(diskUsage, {
  duration: duration,
  transition: TransitionPresets.easeOutExpo,
});

// 右上角数量
const statisticData = ref([
  {
    value: 99,
    iconClass: "message",
    title: "消息",
    key: "message",
  },
  {
    value: 50,
    iconClass: "todolist",
    title: "待办",
    suffix: "/100",
    key: "upcoming",
  },
  {
    value: 10,
    iconClass: "project",
    title: "项目",
    key: "project",
  },
]);

// 系统监控卡片
const cardData = ref<CardProp[]>([
  {
    title: "CPU使用率",
    tagType: "primary",
    tagText: "实时",
    count: cpuUsageOutput,
    dataDesc: "CPU使用情况",
    iconClass: "cpu",
  },
  {
    title: "内存使用率",
    tagType: "warning",
    tagText: "实时",
    count: memoryUsageOutput,
    dataDesc: "内存使用情况",
    iconClass: "memory",
  },
  {
    title: "磁盘使用率",
    tagType: "danger",
    tagText: "实时",
    count: diskUsageOutput,
    dataDesc: "磁盘使用情况",
    iconClass: "disk",
  }
]);

onMounted(async () => {
  await getSystemInfo();
  // TODO 由于 MinIO 部署在本地 Docker 环境中。所以在使用本地 ip 进行访问
  // 将路径中的 minio 替换成 localhost
  userStore.user.avatar = userStore.user.avatar?.replace("minio", "localhost");
});

const updateAvatar = (avatarUrl: string) => {
  // 头像修改完成后将路径中的 minio 替换成 localhost
  userStore.user.avatar = avatarUrl.replace("minio", "localhost");
};

const getSystemInfo = async () => {
  try {
    loading.value = true;
    const response = await getSystemInfoApi();

    // 设置操作系统相关信息
    osName.value = response.data.os.osName || '-';
    osVersion.value = response.data.os.osVersion || '-';
    osArch.value = response.data.os.osArch || '-';

    // 设置CPU相关信息
    cpuNum.value = response.data.cpu.availableProcessors || '-';
    cpuUsage.value = response.data.cpu.cpuUsage || 0;

    // 设置内存相关信息
    memoryTotal.value = response.data.memory.totalMemory || '-';
    memoryUsed.value = response.data.memory.usedMemory || '-';
    memoryUsage.value = response.data.memory.memoryUsage || 0;

    // 设置磁盘相关信息
    const diskData = response.data.disk || {};
    const formattedDiskInfo: Record<string, { total: number | string; used: number | string }> = {};

    for (const [path, info] of Object.entries(diskData)) {
      formattedDiskInfo[path] = {
        total: (info as any).totalSpace || '-',
        used: (info as any).usedSpace || '-'
      };
    }
    diskInfo.value = formattedDiskInfo;
    // 计算所有磁盘的平均使用率
    const diskUsageValues = Object.values(response.data.disk).map((disk: any) => disk.diskUsage);
    const avgDiskUsage = diskUsageValues.reduce((acc: number, curr: number) => acc + curr, 0) / diskUsageValues.length;
    diskUsage.value = avgDiskUsage || 0;
  } catch (error) {
    console.error('获取系统信息失败:', error);
    ElMessage.error('获取系统信息失败');
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  padding: 24px;

  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }

  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }

  .data-box {
    display: flex;
    justify-content: space-between;
    padding: 20px;
    font-weight: bold;
    color: var(--el-text-color-regular);
    background: var(--el-bg-color-overlay);
    border-color: var(--el-border-color);
    box-shadow: var(--el-box-shadow-dark);
  }

  .svg-icon {
    fill: currentcolor !important;
  }

  .el-row:nth-child(2) .el-card {
    transition: all 0.3s ease;
    cursor: pointer;

    &:hover {
      transform: translateY(-5px);
      box-shadow: var(--el-box-shadow-dark);
    }
  }
}

.map-container {
  height: 900px;
}
</style>
